<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Post as Posts;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\UserInfo;
use think\Db;

class Post extends Common
{
    private $cModel;   //当前控制器关联模型
    
    public function _initialize()
    {
        parent::_initialize();
        $this->cModel = new Posts;   //别名：避免与控制名冲突
    }
    
    public function index()
    {
        $where = [];
        if (input('get.search')){
            $where['username|name|email|moblie'] = ['like', '%'.input('get.search').'%'];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
        
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    
    public function create()
    {
        if (request()->isPost()){
            Db::startTrans();
            try{
                $data = input('post.');
                $result = $this->cModel->validate(CONTROLLER_NAME.'.add')->allowField(true)->save($data);
                // 提交事务
                if ($result){
                    Db::commit();
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajaxReturn($e->getMessage());
            }
        }else{
            return $this->fetch('create');
        }
    }
    
    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            if ($data['actions'] == 'password'){    //修改密码
                if ( $data['id'] != UID ){          //修改他人密码需验证旧密码
                    $oldData = $this->cModel->where(['id' => $data['id'], 'password' => md5($data['oldpassword'])])->find();
                    if (empty($oldData)){
                        ajaxReturn(lang('oldpassword_val'));
                    }
                }
                $result = $this->cModel->validate(CONTROLLER_NAME.'.password')->allowField(true)->save($data, $data['id']);
            }elseif ($data['actions'] == 'avatar'){   //修改头像
                // $uiModel = new UserInfo();
                // $where = ['uid' => $data['id']];
                 unset($data['actions']);
                // $result = $uiModel->allowField(true)->where($where)->update($data);
                $result = $this->cModel->validate(CONTROLLER_NAME.'.password')->allowField(true)->save($data, $data['id']);
            }elseif ($data['actions'] == 'infos'){   //修改附加信息
                $uiModel = new UserInfo();
                $where = ['uid' => $data['id']];
                if ( isset($data['birthday']) ){
                    $data['birthday'] = strtotime($data['birthday']);
                }
                unset($data['actions']);
                $result = $uiModel->allowField(true)->where($where)->update($data);
            }else{   //修改信息
                if (count($data) == 2){
                    foreach ($data as $k =>$v){
                        $fv = $k!='id' ? $k : '';
                    }
                    $result = $this->cModel->validate(CONTROLLER_NAME.'.'.$fv)->allowField(true)->save($data, $data['id']);
                }else{
                    $result = $this->cModel->validate(CONTROLLER_NAME.'.edit')->allowField(true)->save($data, $data['id']);
                }
            }
            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            if ($id > 0){
                $data = $this->cModel->get($id);
                $this->assign('data', $data);
                return $this->fetch();
            }
        }
    }
    
    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                Db::startTrans();
                try{
                    $id_arr = explode(',', $id);   //用户数据
                    // $where1 = [ 'uid' => ['in', $id_arr] ];
                    // $uiModel = new UserInfo();
                    // $data = $uiModel->where($where1)->select();   //查询用户附加表信息【用于删除头像】
                    $where2 = [ 'id' => ['in', $id_arr] ];
                    $result = $this->cModel->where($where2)->delete();   //删除主表数据
                    // $where3 = [ 'uid' => ['in', $id_arr] ];
                    // $agaModel = new AuthGroupAccess();
                    // $agaModel->where($where1)->delete();   //删除用户分配角色
                    // $result2 = $uiModel->where($where1)->delete();   //删除用户附加表
                    // 提交事务
                    if ($result){
                        Db::commit();
                        foreach ($data as $k => $v){
                            if ($v['avatar'] != '/static/global/face/default.png'){
                                unlink(WEB_PATH.$v['avatar']);   //删除头像文件
                            }
                        }
                        return ajaxReturn(lang('action_success'), url('index'));
                    }else{
                        return ajaxReturn($this->cModel->getError());
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajaxReturn($e->getMessage());
                }
            }
        }
    }
    

    public function fixcode(){
        $id = input('post.');
        $result = $this->cModel->get($id)->toArray();
        $data= '';
        foreach ($result as $key => $val) {
            if ($key!='id' && $key!='fixcode_src' && $val  && $key!='update_time') {
              $data.=lang($key).': '.$val."
";
            }
        }
        ob_clean();
        vendor('phpqrcode.phpqrcode');
        $filename = $result['number'].'.png';  //  生成的文件名  
        $errorCorrectionLevel = 'L';  // 纠错级别：L、M、Q、H  
        $matrixPointSize = 4; // 点的大小：1到10  
        $rs = \QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        

        $image = \think\Image::open($filename);
        //生成目录
        $savePath = 'uploads'.DS.'post';
        //var_dump($savePath);die;
        if ( !file_exists($savePath) ){
            mkdir($savePath);
        }
        $filePath = $savePath.DS.$filename;
        $rs = $image->save(ROOT_PATH.'public'.DS.$savePath.DS.$filename);
        if ($rs) {
            $this->cModel->update(['fixcode_src'=>DS.$savePath.DS.$filename,'update_time'=>time()],$id);
            unlink($filename);
            return ajaxReturn(lang('action_success'), url('index'));
        }

    }

    public function import(){
        $file = $this->request->file('imgFile');
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'files');
            if($info){
                $path = ROOT_PATH . 'public' . DS . 'uploads'.DS.'files'.DS.$info->getSaveName();
            }else{
                // 上传失败获取错误信息
                return ajaxReturn($file->getError());
            }
        }



      ini_set('memory_limit','800M');
      //
      error_reporting(E_ALL);
      /** Include path **/
      set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH.'/PHPExcel/Classes/');
        
      /** PHPExcel */
      vendor('PHPExcel.Classes.PHPExcel');

      /** PHPExcel_IOFactory */
      vendor('PHPExcel/Classes/PHPExcel/IOFactory');

      //vendor('PHPExcel/Classes/PHPExcel/Shape/Date.php');

      //$shared = new \PHPExcel_Shared_Date();

      $objPHPExcel = new \PHPExcel();
      //var_dump($info);ExcelToArray()
      //if ($info['xls']['ext']=='xls') {
      $objReader = \PHPExcel_IOFactory::createReader('Excel5');
      // }else{
      //     $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
      // }
      $objPHPExcel = $objReader->load($path,$encode='utf-8');
      $sheet = $objPHPExcel->getSheet(0);
      $highestRow = $sheet->getHighestRow(); // 取得总行数
      //$highestColumn = $sheet->getHighestColumn(); // 取得总列数
    $arr=array();

    for($i=2;$i<=$highestRow;$i++){
        $data=array();
        $data['number']=  $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
        $data['func']=  $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
        $data['requirement']=  $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
        $data['update_time'] = time();
        $arr[] = $data;
    }
    $rs = $this->cModel->insertAll($arr);
    if ($rs) {
        return ajaxReturn(lang('action_success'), url('index'));
    }else{
        return ajaxReturn($this->cModel->getError());
    }

    }


    public function downloadfix(){
        //下面是实例操作过程：
        $dfile = tempnam('/tmp', 'tmp'); //产生一个临时文件，用于缓存下载文件
        vendor('download.zipfile');
        $zip = new \zipfile();
        //----------------------
        $filename = 'fixcode.zip'; //下载的默认文件名
        $dataList = $this->cModel->select();

        $image = array();
        foreach ($dataList as $key => $val) {
            if ($val['fixcode_src']) {
                 $image[$key]['image_src'] = ROOT_PATH . 'public'.$val['fixcode_src'];
                 $image[$key]['image_name'] = $val['number'].'.jpg';
            }
        }

        foreach($image as $v){
          $zip->add_file(file_get_contents($v['image_src']), $v['image_name']);
          // 添加打包的图片，第一个参数是图片内容，第二个参数是压缩包里面的显示的名称, 可包含路径
          // 或是想打包整个目录 用 $zip->add_path($image_path);
        }
        //----------------------
        $zip->output($dfile);
         
        // 下载文件
        ob_clean();
        header('Pragma: public');
        header('Last-Modified:'.gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control:no-store, no-cache, must-revalidate');
        header('Cache-Control:pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding:binary');
        header('Content-Encoding:none');
        header('Content-type:multipart/form-data');
        header('Content-Disposition:attachment; filename="'.$filename.'"'); //设置下载的默认文件名
        header('Content-length:'. filesize($dfile));
        $fp = fopen($dfile, 'r');
        while(connection_status() == 0 && $buf = @fread($fp, 8192)){
          echo $buf;
        }
        fclose($fp);
        @unlink($dfile);
        @flush();
        @ob_flush();
        exit();
       
    }

    public function downloadactive(){
        $dfile = tempnam('/tmp', 'tmp'); //产生一个临时文件，用于缓存下载文件
        vendor('download.zipfile');
        $zip = new \zipfile();
        //----------------------
        $filename = 'activecode.zip'; //下载的默认文件名
        $dataList = $this->cModel->select();

        $image = array();
        foreach ($dataList as $key => $val) {
            if ($val['activecode']) {
                 $image[$key]['image_src'] = ROOT_PATH . 'public'.$val['activecode'];
                 $image[$key]['image_name'] = $val['number'].'.jpg';
            }
        }

        foreach($image as $v){
          $zip->add_file(file_get_contents($v['image_src']), $v['image_name']);
          // 添加打包的图片，第一个参数是图片内容，第二个参数是压缩包里面的显示的名称, 可包含路径
          // 或是想打包整个目录 用 $zip->add_path($image_path);
        }
        //----------------------
        $zip->output($dfile);
         
        // 下载文件
        ob_clean();
        header('Pragma: public');
        header('Last-Modified:'.gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control:no-store, no-cache, must-revalidate');
        header('Cache-Control:pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding:binary');
        header('Content-Encoding:none');
        header('Content-type:multipart/form-data');
        header('Content-Disposition:attachment; filename="'.$filename.'"'); //设置下载的默认文件名
        header('Content-length:'. filesize($dfile));
        $fp = fopen($dfile, 'r');
        while(connection_status() == 0 && $buf = @fread($fp, 8192)){
          echo $buf;
        }
        fclose($fp);
        @unlink($dfile);
        @flush();
        @ob_flush();
        exit();
    }

    public function download(){
         ob_end_clean();
         ob_start();
         vendor('PHPExcel/Classes/PHPExcel');
        $cfg_columns = array(
            'id'=>array('name'=>lang('id')),
            'number'=>array('name'=>lang('number')),
            'func'=>array('name'=>lang('func')),
            'requirement'=>array('name'=>lang('requirement')),
            'update_time'=>array('name'=>lang('update_time')),
            //'dept_name'    => array('name'  => '部门','type'    => 'label','width' => 100),
        );
        $dataList = $this->cModel->all();
        $list = array();
        foreach ($dataList as $key => $value) {
            $list[] = $value->toArray();
        }

        $filename = 'post.xls';
        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="'.$filename.'"');
        header('Content-Disposition:inline;filename="'.$filename.'"');

        $objPHPExcel = new \PHPExcel();

        $objPHPExcel->getActiveSheet(0)->mergeCells('B1:D1');
        $export_time = date('Y-m-d H:i:s');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '导出时间:');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1', $export_time);

        $cols = 'A';
        foreach ($cfg_columns as $val){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cols++.'2',$val['name']);
        }

        //第三行, 输出详细数据
        $rows = 3;
        foreach ($list as $fields){
            $cols = 'A';
            //按cfg_column的配置项导出
            foreach ($cfg_columns as $k => $val){
                if(empty( $fields[$k])){
                    $objPHPExcel->getActiveSheet()->setCellValue($cols++.$rows, 0);
                }else{
                    $objPHPExcel->getActiveSheet()->setCellValue($cols++.$rows, $fields[$k]);
                }

            } 

            $rows ++;
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

}